<?php
namespace App\Think\SdkGame;

class JDB{

    // 1. API Server Information
    // Server Type
    // API Server : http://api.jygrq.com 
    // 后台地址 ： https://agent.jygrq.com/
    // 账号 ： searmbBT
    // 密码 ： aa123456
    // 用户码 ：sea
    // FTP URL : ftp://203.73.176.196:2121 
    // 账号 ： searmbag@SEA 密码 ： 3c0f84searmbag
    // 2. Customer Domain Name & Encryption Information   
    // Item ： Data
    // DC ： SEA
    // IV ： f0cdbeacf8bcd4a4
    // KEY ： dedbb2ad00841ccc   
    // 文档地址：https://apidoc.sqntbw.com/apidoc/jdb/releases/2.6.19/JDB_api_cn_v2.6.19.pdf
    
    public function __construct()
    {
        // api地址
        $this->api_url = 'http://api.jygrq.com/apiRequest.do';
        $this->dc  = 'SEA';
        $this->iv  = 'f0cdbeacf8bcd4a4';
        $this->key = 'dedbb2ad00841ccc';

        $this->parent = 'searmbbt';
        $this->plat_type = 'JDB';
    }

    /**
     * 注册
     */
    public function register($param){
        $req_data = array(
            'action' => 12,
            'ts'     => time()*1000,
            'parent' => $this->parent,
            'uid'    => $param['account'],
            'name'   => $param['account'],
            'credit_allocated' => 0
        );
        $url = $this->build_request($req_data);
        $res = $this->sendRequest($this->api_url, $url);
        return $res;
    }
    /**
     * 获取登录链接
     */
    public function login($param){
        // $reg_res = $this->register($param);
        // if($reg_res['code'] == -1) return $reg_res;
        $req_data = array(
            'action' => 11,
            'ts'     => time()*1000,
            'lang'   => 'ch',
            'uid'    => $param['account'],
            'moreGame'   => 1,
        );
        $url = $this->build_request($req_data);
        $res = $this->sendRequest($this->api_url, $url);
        return ['code'=>1, 'url'=>$res['path'] ];
    }
    /**
     * 获取余额
     */
    public function balance($param){
        $req_data = array(
            'action' => 15,
            'ts'     => time()*1000,
            'parent' => $this->parent,
            'uid'    => $param['account']
        );
        $url = $this->build_request($req_data);
        $res = $this->sendRequest($this->api_url, $url);
        return ['code'=>$res['code'], 'balance'=>(float)$res['data'][0]['balance'] ];
    }

    /**
     * 转入资金(上分)
     */
    public function transIn($param){
        $req_data = array(
            'action' => 19,
            'ts'     => time()*1000,
            'parent' => $this->parent,
            'uid'    => $param['account'],
            'serialNo' => $param['orderid'],
            'allCashOutFlag' => 0,
            'amount' => $param['money'],
        );
        $url = $this->build_request($req_data);
        $res = $this->sendRequest($this->api_url, $url);
        return $res;
    }
    /**
     * 转出资金(下分)
     */
    public function transOut($param){
        $req_data = array(
            'action' => 19,
            'ts'     => time()*1000,
            'parent' => $this->parent,
            'uid'    => $param['account'],
            'serialNo' => $param['orderid'],
            'allCashOutFlag' => 0,
            'amount' => -$param['money'],
        );
        $url = $this->build_request($req_data);
        $res = $this->sendRequest($this->api_url, $url);
        return $res;
    }
    /**
     * 可转出资金查询(下分额度)
     */
    public function transOutInfo($param){
        $req_data = array(
            'action' => 15,
            'ts'     => time()*1000,
            'parent' => $this->parent,
            'uid'    => $param['account']
        );
        $url = $this->build_request($req_data);
        $res = $this->sendRequest($this->api_url, $url);
        return $res;
    }

    /**
     * 游戏注单拉取
     */
    public function gameLogSync($param){

        /*
        // 获取游戏列表
        $req_data = array(
            'action' => 49,
            'ts'     => time()*1000,
            'parent' => $this->parent,
            'lang'   => 'ch'
        );
        $url = $this->build_request($req_data);
        $res = $this->sendRequest($this->api_url, $url);
        foreach ($res['data'] as $key => $v) {
            // echo $v['gType'].',';
            foreach ($v['list'] as $kk => $vv) {
                echo $vv['mType'].','.$vv['name']."\n";
            }
        }
        return $res;
        exit;
        */

        //获取游戏记录
        $now_time = time();
        
        $end_time   = $now_time-strtotime($param['endTime'])>180 ? strtotime($param['endTime']) : $now_time-180;
        $start_time = $now_time-strtotime($param['startTime'])>180 ? strtotime($param['startTime'])-180 : $now_time-180;
        list($start_time, $end_time) = [$start_time-3600*12, $end_time-3600*12];
        $req_data = array(
            'action' => 29,
            'ts'     => time()*1000,
            'parent' => $this->parent,
            "starttime" => date("d-m-Y H:i:00", $start_time),
            "endtime"   => date("d-m-Y H:i:00", $end_time),
        );
        $url = $this->build_request($req_data);
        $res = $this->sendRequest($this->api_url, $url);

        //数据返回处理
        $list = @$res['data'];
        $rs = $raw_data = [];
        $status = 1;
        if(is_array($list) && count($list) > 0){
            foreach ($list as $k => $v) {
                //流水
                $money_winlose = $v['total'];
                $money_bet = -$v['bet'];
                if($money_winlose < 0)  $money_valid = -$money_winlose;
                if($money_winlose >= 0) $money_valid = $money_winlose<$money_bet ? $money_winlose : $money_bet;
                //游戏记录处理
                $rs[$k] = [
                    'plat_type'     => $this->plat_type,
                    'game_type'     => $v['mtype'],
                    'game_name'     => @$this->game_name($v['mtype']),
                    'game_user'     => $v['playerId'],
                    'bet_id'        => $v['seqNo'],
                    'money_bet'     => (float)$money_bet,
                    'money_valid'   => (float)$money_valid, 
                    'money_winlose' => $money_winlose,
                    'money_fee'     => (float)-@$v['tax'],
                    'createtime'    => strtotime($v['gameDate'])+3600*12,
                    'updatetime'    => strtotime($v['lastModifyTime'])+3600*12,
                    'status'        => $status,
                ];
                //源数据处理
                $raw_data[$k] = $v;
                $raw_data[$k]['plat_type'] = $this->plat_type;
                $raw_data[$k]['bet_id']    = $v['seqNo'];
                $raw_data[$k]['status']    = $status;
                $raw_data[$k]['updatetime'] = strtotime($v['lastModifyTime'])+3600*12;
            }
        }
        $res['list'] = $rs;
        $res['raw_data']  = $raw_data;
        return $res;
    }




    /**
     * 业务 ======== start =========//
     */
    private function bet_status($status){
        return $status;
    }

    //游戏列表
    public function game_list(){
        $list = [
            '7003'=>'财神捕鱼',
            '7005'=>'捕魚一路發',
            '7004'=>'五龙捕鱼',
            '7002'=>'龙王捕鱼2',
            '7001'=>'龙王捕鱼',
            '8047'=>'变脸II',
            '8048'=>'芝麻开门II',
            '8049'=>'唐伯虎点秋香II',
            '8035'=>'幸运凤',
            '8031'=>'金饺子',
            '8030'=>'疯狂科学家',
            '8029'=>'奇幻糖果岛',
            '8028'=>'幸运淘金鼠',
            '8027'=>'料理厨王',
            '8044'=>'江山美人',
            '8025'=>'神偷妙贼',
            '8024'=>'水晶王国',
            '8046'=>'关公',
            '8007'=>'幸运麟',
            '8001'=>'幸运龙',
            '8034'=>'金钱侠',
            '8021'=>'黄金香蕉帝国',
            '8003'=>'变脸',
            '8022'=>'麻雀无双',
            '8006'=>'台湾黑熊',
            '8017'=>'过新年',
            '8002'=>'唐伯虎点秋香',
            '8018'=>'拿破仑',
            '8005'=>'骆马大冒险',
            '8020'=>'芝麻开门',
            '8004'=>'悟空',
            '8015'=>'月光秘宝',
            '8014'=>'招财狮',
            '8016'=>'上班族狂想曲',
            '8037'=>'魔术秀',
            '8023'=>'奥林匹亚神庙',
            '8019'=>'文房四宝',
            '8036'=>'龙王',
            '8026'=>'热舞教父',
            '8051'=>'喜洋羊',
            '8050'=>'马上有钱',
            '14040'=>'七海夺宝',
            '14041'=>'雷神之锤',
            '14042'=>'聚宝盆',
            '14019'=>'宝石物语',
            '14023'=>'赌王扑克',
            '14025'=>'幸运赛车',
            '14026'=>'发大财',
            '14045'=>'超级牛B 豪华版',
            '14033'=>'飞鸟派对',
            '14044'=>'古怪金刚',
            '14043'=>'蹦迪吧',
            '14004'=>'塞尔达传说',
            '14016'=>'王牌特工',
            '14002'=>'玛雅',
            '14001'=>'斗鸡',
            '14008'=>'神龙大侠',
            '14022'=>'采矿土豪',
            '14021'=>'钱滚钱',
            '14007'=>'一拳超人',
            '14005'=>'包大人',
            '14017'=>'少女前线',
            '14010'=>'飞龙在天',
            '14011'=>'银河护卫队',
            '14012'=>'街头霸王',
            '14006'=>'亿万富翁',
            '14015'=>'星球大战',
            '14003'=>'屌丝熊猫',
            '14034'=>'狗来富',
            '14020'=>'魔法乳神',
            '14018'=>'妲己',
            '14013'=>'春宵苦短',
            '14032'=>'发发',
            '14030'=>'三倍金刚',
            '14038'=>'埃及夺宝',
            '14035'=>'龙舞',
            '14039'=>'开运夺宝',
            '14036'=>'超级牛B',
            '14027'=>'好运777',
            '14029'=>'东方神兽',
            '15012'=>'五福临门',
            '15013'=>'九尾狐',
            '15005'=>'幸运福娃',
            '15009'=>'忍者大进击',
            '15006'=>'印加帝国',
            '15004'=>' 火牛阵',
            '15002'=>'齐天大圣',
            '15001'=>'金鸡报囍',
            '15010'=>'熊猫厨王',
            '15011'=>'后羿傳',
            '9001'=>'小玛莉',
            '9007'=>'超激发水果盘',
            '9004'=>'啤酒大亨',
            '9006'=>'花果山传奇',
            '9002'=>'新年快乐',
            '9003'=>'飞禽走兽',
            '12001'=>'财神宾果彩',
            '12003'=>'快乐六星彩',
            '12002'=>'金鸡福彩',
            '18002'=>'抢庄牛牛',
            '18005'=>'抢庄六牛',
            '18001'=>'通比牛牛',
            '18013'=>'通比六牛',
            '18004'=>'押庄射龙门',
        ];
        return $list;
    }
    //游戏名称
    public function game_name($gameid){
        $list = $this->game_list();
        return isset($list[$gameid]) ? $list[$gameid] : '未知游戏';
    }


    /**
     * --------------
     * 内部方法
     * --------------
     */
    private function sendRequest($url,$post_data=array(), $req_type=0){
        $ch = curl_init();
        //POST / GET
        if($req_type == 1){ 
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        }else{
            $url .= '?'.http_build_query($post_data);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $contents = curl_exec($ch);
        curl_close($ch);
        $contents = json_decode($contents, true);
        //业务处理
        $res = $contents;
        if(!isset($res['status']) || $res['status'] != '0000'){
            $res['code'] = -1;
        }else{
            $res['code'] = 1;
        }
        return $res;
    }
    
    private function build_request(array $param){
        $jsonString = json_encode($param);
        $mc = new JDBMCrypt($this->iv, $this->key);
        $encryptData = $mc->encrypt($jsonString);
        $data = array('dc'=>$this->dc, 'x'=>$encryptData);
        return $data;
    }
}

class JDBMCrypt{
    // private $key = ''; // change itprivate 
    // private $iv = ''; // change it
    function __construct($iv='', $key='') {
        $this->iv = $iv;
        $this->key = $key;
    }
    
    function encrypt($str) {
        $key = $this->key;
        $iv = $this->iv;
        $str= $this->padString($str);
        $encrypted = openssl_encrypt($str, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($encrypted);
    }

    function decrypt($code) {
        $code = str_replace(array('-','_'),array('+','/'),$code);
        $code = base64_decode($code);
        $key = $this->key;
        $iv = $this->iv;
        $decrypted = openssl_decrypt($code, 'AES-128-CBC', $key, OPENSSL_NO_PADDING, $iv);
        return utf8_encode(trim($decrypted));
    }
    
    private function padString($source) {
        $paddingChar = ' ';
        $size        = 16;
        $x           = strlen($source) % $size;
        $padLength   = $size -$x;
        for ($i = 0; $i< $padLength; $i++) {
            $source .= $paddingChar;
        }
        return $source;
    }
}